"""
This module provides a Flask application for movie search and user authentication.
"""

from flask import Flask, render_template, request
from peewee import MySQLDatabase, Model, CharField
from flasgger import Swagger

# 初始化 Flask 应用
app = Flask(__name__)
swagger = Swagger(app)

# 数据库配置
db = MySQLDatabase(
    "1", host="localhost", port=3306, user="root", passwd="3218560376jJ"
)


class Movie(Model):
    """
    Represents a movie entity with title and year fields.

    Attributes:
        title (CharField): The title of the movie.
        year (CharField): The release year of the movie.
    """

    title = CharField(max_length=200)
    year = CharField(max_length=10)

    class Meta:
        """Meta information for the Movie model."""
        database = db
        table_name = 'douban_movie'


@app.route('/')
def home():
    """
    Renders the home page of the application.
    """
    return render_template('home.html')


@app.route('/signin', methods=['GET'])
def signin_form():
    """
    Renders the sign-in form.

    ---
    tags:
      - Authentication
    responses:
      200:
        description: Displays the sign-in form
    """
    return render_template('form.html', message=None, username='')


@app.route('/signin', methods=['POST'])
def signin():
    """
    Handles user sign-in logic.

    ---
    tags:
      - Authentication
    parameters:
      - name: username
        in: formData
        type: string
        required: true
      - name: password
        in: formData
        type: string
        required: true
    responses:
      200:
        description: Successfully logged in
        examples:
          username: admin
      401:
        description: Bad username or password
    """
    username = request.form['username']
    password = request.form['password']
    if username == 'admin' and password == 'password':
        return render_template('signin-ok.html', username=username)
    return render_template('form.html', message='Bad username or password', username=username)


@app.route('/movie_search', methods=['POST'])
def movie_search():
    """
    Handles movie search based on the release year.

    ---
    tags:
      - Movies
    parameters:
      - name: username
        in: formData
        type: string
        required: true
        default: admin
      - name: release_year
        in: formData
        type: string
        required: true
        description: The release year of the movie (e.g. "2020")
    responses:
      200:
        description: List of movies found
        examples:
          movies:
            - {title: "Movie Title 1", year: "2020"}
            - {title: "Movie Title 2", year: "2020"}
      404:
        description: No movies found for the given year
    """
    username = request.form.get('username', 'admin')
    release_year = request.form.get('release_year', '').strip()

    if not release_year:
        return render_template('signin-ok.html', username=username, error="请输入上映年份")

    movies = Movie.select().where(Movie.year == release_year).order_by(Movie.title)

    if not movies:
        return render_template('signin-ok.html', username=username, error="未找到该年份的电影")
    return render_template('signin-ok.html', username=username, movies=movies, release_year=release_year)


if __name__ == '__main__':
    # 打印 API 文档地址
    print("API 文档地址：http://localhost:5000/apidocs")
    app.run(debug=True)
